<template>
  <div class="amap-picker">
    <!-- 地址搜索框 -->
    <div class="search-container">
      <el-autocomplete
          v-model="searchKeyword"
          :fetch-suggestions="handleSearch"
          :trigger-on-focus="false"
          clearable
          placeholder="请输入地址搜索"
          style="width: 100%"
          @select="handleSelectAddress"
      >
        <template #default="{ item }">
          {{ item.address }}
        </template>
      </el-autocomplete>

      <!-- 定位状态提示 -->
      <div v-if="locationLoading" class="location-tip">
        <el-icon class="is-loading">
          <Loading/>
        </el-icon>
        正在获取当前位置...
      </div>
    </div>

    <!-- 地图容器 -->
    <div
        v-show="showMap"
        ref="mapContainer"
        :style="{ height: mapHeight }"
        class="map-container"
    ></div>

    <!-- 选中地址信息 -->
    <div v-if="selectedAddress" class="selected-info">
      <el-card>
        <div class="info-item">
          <span class="label">地址：</span>
          <span>{{ selectedAddress.formattedAddress }}</span>
        </div>
        <div class="info-item">
          <span class="label">经纬度：</span>
          <span>{{ selectedLng }}, {{ selectedLat }}</span>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import {onMounted, onUnmounted, ref, watch} from 'vue'
import {ElMessage} from 'element-plus'
import {Loading} from '@element-plus/icons-vue'
import request from "@/utils/request.js";

// Props
const props = defineProps({
  // 地图高度
  height: {
    type: String,
    default: '400px'
  },
  // 初始中心点经纬度 [lng, lat]
  center: {
    type: Array,
    default: () => [116.397428, 39.90923] // 北京天安门
  },
  // 初始缩放级别
  zoom: {
    type: Number,
    default: 13
  },
  // v-model绑定的值 {lng, lat, address}
  modelValue: {
    type: Object,
    default: () => ({})
  },
  // 是否展示地图
  showMap: {
    type: Boolean,
    default: false
  },
  // 是否自动定位
  autoLocation: {
    type: Boolean,
    default: true
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'change'])

// 响应式数据
const mapContainer = ref(null)
const searchKeyword = ref('')
const locationLoading = ref(false)
const selectedAddress = ref(null)
const selectedLng = ref('')
const selectedLat = ref('')

// 地图相关
let map = null
let marker = null
let geolocation = null
let placeSearch = null
let geocoder = null

// 计算属性
const mapHeight = ref(props.height)

// 初始化高德地图
const initMap = async () => {
  try {
    // 动态加载高德地图API
    await loadAmapScript()

    // 创建地图实例
    map = new AMap.Map(mapContainer.value, {
      zoom: props.zoom,
      center: props.center,
      mapStyle: 'amap://styles/normal', // 标准样式
      viewMode: '2D' // 2D视图
    })

    // 初始化插件
    await initPlugins()

    // 绑定地图点击事件
    map.on('click', handleMapClick)

    // 如果有初始值，设置标记
    if (props.modelValue.lng && props.modelValue.lat) {
      setMarker(props.modelValue.lng, props.modelValue.lat)
      getAddressByLocation(props.modelValue.lng, props.modelValue.lat)
    } else if (props.autoLocation) {
      // 自动获取当前位置
      handleGetLocation()
    }

  } catch (error) {
    console.error('地图初始化失败:', error)
    ElMessage.error('地图加载失败')
  }
}

// 动态加载高德地图脚本
const loadAmapScript = () => {
  return new Promise((resolve, reject) => {
    if (window.AMap) {
      resolve()
      return
    }

    const script = document.createElement('script')
    script.src = `https://webapi.amap.com/maps?v=2.0&key=f2101aa8407d394d4a29a80d534d1aa3&plugin=AMap.PlaceSearch,AMap.Geolocation,AMap.Geocoder`
    script.onload = resolve
    script.onerror = reject
    document.head.appendChild(script)
  })
}

// 初始化插件
const initPlugins = () => {
  return new Promise((resolve) => {
    // 定位插件
    geolocation = new AMap.Geolocation({
      enableHighAccuracy: true,
      timeout: 10000,
      maximumAge: 0
    })

    // 地点搜索插件 (用于自动完成)
    placeSearch = new AMap.PlaceSearch({
      city: '全国',
      citylimit: false,
      extensions: "all",
      pageSize: 10
    })

    // 地理编码插件
    geocoder = new AMap.Geocoder()

    resolve()
  })
}

// 获取当前位置
const handleGetLocation = () => {
  if (!geolocation) return

  locationLoading.value = true
  geolocation.getCurrentPosition((status, result) => {
    locationLoading.value = false
    if (status === 'complete') {
      const {lng, lat} = result.position

      const location = `${lng},${lat}`
      request.post(`/user/setLocation?location=${location}`)
      setMarker(lng, lat)
      map.setCenter([lng, lat])
      getAddressByLocation(lng, lat)
      console.log('🎯 自动定位成功:', {lng, lat})
    } else {
      console.warn('❌ 定位失败:', result.message)
      ElMessage.warning('无法获取当前位置，请手动选择')
    }
  })
}

// 地址搜索 - 修复自动联想功能
const handleSearch = (queryString, callback) => {
  if (!queryString || queryString.length < 2 || !placeSearch) {
    callback([])
    return
  }

  placeSearch.search(queryString, (status, result) => {
    if (status === 'complete' && result.poiList && result.poiList.pois) {
      const suggestions = result.poiList.pois.map(poi => ({
        value: poi.name,
        name: poi.name,
        district: poi.pname + poi.cityname + poi.adname,
        location: poi.location,
        address: poi.pname + poi.cityname + poi.adname + poi.name
      }))
      callback(suggestions)
    } else {
      callback([])
    }
  })
}

// 选择搜索结果
const handleSelectAddress = (item) => {
  if (item.location) {
    const lng = item.location.lng
    const lat = item.location.lat
    setMarker(lng, lat)
    map.setCenter([lng, lat])

    // 直接使用搜索结果的地址信息
    selectedAddress.value = {
      formattedAddress: item.address
    }

    // 更新坐标显示
    selectedLng.value = lng.toFixed(6)
    selectedLat.value = lat.toFixed(6)

    // 输出日志
    console.log('🔍 搜索选择地址:', {
      lng: parseFloat(lng.toFixed(6)),
      lat: parseFloat(lat.toFixed(6)),
      address: item.address
    })

    // 更新v-model值
    const newValue = {
      longitude: parseFloat(lng.toFixed(6)),
      latitude: parseFloat(lat.toFixed(6)),
      address: item.address
    }

    emit('update:modelValue', newValue)
    emit('change', newValue)
  }
}

// 地图点击事件
const handleMapClick = (e) => {
  const {lng, lat} = e.lnglat
  setMarker(lng, lat)
  getAddressByLocation(lng, lat)

  console.log('🖱️ 地图点击选择:', {
    lng: parseFloat(lng.toFixed(6)),
    lat: parseFloat(lat.toFixed(6))
  })
}

// 设置标记点
const setMarker = (lng, lat) => {
  // 移除旧标记
  if (marker) {
    map.remove(marker)
  }

  // 创建新标记
  marker = new AMap.Marker({
    position: [lng, lat],
    icon: new AMap.Icon({
      size: new AMap.Size(25, 34),
      image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png'
    })
  })

  map.add(marker)

  // 更新选中坐标
  selectedLng.value = lng.toFixed(6)
  selectedLat.value = lat.toFixed(6)
}

// 根据坐标获取地址
const getAddressByLocation = (lng, lat) => {
  if (!geocoder) return

  geocoder.getAddress([lng, lat], (status, result) => {
    if (status === 'complete' && result.regeocode) {
      selectedAddress.value = result.regeocode

      const newValue = {
        lng: parseFloat(lng.toFixed(6)),
        lat: parseFloat(lat.toFixed(6)),
        address: result.regeocode.formattedAddress
      }

      // 输出日志
      console.log('📍 坐标解析地址:', newValue)

      emit('update:modelValue', newValue)
      emit('change', newValue)
    }
  })
}

// 监听modelValue变化
watch(() => props.modelValue, (newValue) => {
  if (newValue.lng && newValue.lat && map) {
    setMarker(newValue.lng, newValue.lat)
    map.setCenter([newValue.lng, newValue.lat])
    if (newValue.address) {
      selectedAddress.value = {formattedAddress: newValue.address}
    }

    console.log('🔄 外部数据变化:', newValue)
  }
}, {deep: true})

// 生命周期
onMounted(() => {
  initMap()
})

onUnmounted(() => {
  if (map) {
    map.destroy()
  }
})

// 暴露方法
defineExpose({
  // 设置地图中心点
  setCenter: (lng, lat) => {
    if (map) {
      map.setCenter([lng, lat])
    }
  },
  // 获取当前选中位置
  getSelectedLocation: () => ({
    lng: parseFloat(selectedLng.value),
    lat: parseFloat(selectedLat.value),
    address: selectedAddress.value?.formattedAddress
  }),
  // 清除标记
  clearMarker: () => {
    if (marker) {
      map.remove(marker)
      marker = null
      selectedAddress.value = null
      selectedLng.value = ''
      selectedLat.value = ''
    }
  },
  // 手动触发定位
  getCurrentLocation: handleGetLocation
})
</script>

<style scoped>
.amap-picker {
  width: 100%;
}

.search-container {
  margin-bottom: 10px;
}

.location-tip {
  display: flex;
  align-items: center;
  margin-top: 8px;
  font-size: 12px;
  color: #409eff;
}

.location-tip .el-icon {
  margin-right: 5px;
}

.map-container {
  width: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.selected-info {
  margin-top: 10px;
}

.info-item {
  margin-bottom: 8px;
  font-size: 14px;
}

.info-item:last-child {
  margin-bottom: 0;
}

.label {
  font-weight: bold;
  color: #606266;
  margin-right: 8px;
}
</style>